<!-- src/views/UserCenter.vue -->
<template>
  <div class="user-center">
    <el-card class="user-info-card">
      <UserHeader :user-info="userInfo" @avatar-click="avatarDialogVisible = true" />
      <UserInfo :user-info="userInfo" @edit="openEditDialog" />
    </el-card>

    <EditDialog v-model:visible="editDialogVisible" :type="editType" :user-info="userInfo" @submit="handleSubmit" />

    <AvatarUpload 
      :visible="avatarDialogVisible"
      @update:visible="avatarDialogVisible = $event"
      :avatar-url="userInfo.avatarUrl"
      @upload-success="handleAvatarSuccess" 
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/UserStore'
import { updateUserInfo, getUserInfo } from '@/api/User'
import UserHeader from '@/components/user/UserHeader.vue'
import UserInfo from '@/components/user/UserInfo.vue'
import EditDialog from '@/components/user/EditDialog.vue'
import AvatarUpload from '@/components/user/AvatarUpload.vue'

const userStore = useUserStore()
const userInfo = reactive({
  userId: '',
  username: '',
  email: '',
  avatarUrl: '',
  isAdmin: false,
  createdAt: '',
  lastLogin: ''
})

const editDialogVisible = ref(false)
const editType = ref('')
const avatarDialogVisible = ref(false)

const openEditDialog = (type) => {
  editType.value = type
  editDialogVisible.value = true
}

const initUserInfo = () => {
  try {
    if (!userStore.userInfo) {
      ElMessage.error('用户信息不存在')
      return
    }
    
    Object.assign(userInfo, {
      userId: userStore.userInfo.userId,
      username: userStore.userInfo.username,
      email: userStore.userInfo.email,
      avatarUrl: userStore.userInfo.avatarUrl,
      isAdmin: userStore.userInfo.isAdmin,
      createdAt: userStore.userInfo.createdAt,
      lastLogin: userStore.userInfo.lastLogin
    })
  } catch (error) {
    console.error('初始化用户信息失败:', error)
    ElMessage.error('初始化用户信息失败')
  }
}

//个人信息更新的提交
const handleSubmit = async (formData) => {
    try {
        const updateData = {
            userId: userInfo.userId,
            username: userInfo.username,  
            email: userInfo.email,        
            avatarUrl: userInfo.avatarUrl ,
            password:userInfo.password
        };

        switch (editType.value) {
            case 'username':
                updateData.username = formData.username;
                break;
            case 'email':
                updateData.email = formData.email;
                break;
            case 'password':
                updateData.password = formData.password;
                break;
        }

        const res = await updateUserInfo(updateData);
        
        if (res.status === 'success') {
            // 1. 立即更新本地状态
            Object.assign(userInfo, updateData);
            
            // 2. 更新 store 中的用户信息
            await userStore.setUserInfo({
                ...userStore.userInfo,
                ...updateData
            });

            // 3. 重新初始化个人中心信息
            initUserInfo();

            ElMessage.success('修改成功');
            editDialogVisible.value = false;
        } else {
            throw new Error(res.data.message || '更新失败');
        }
    } catch (error) {
        console.error('更新用户信息失败:', error);
        ElMessage.error(error.response?.data?.message || '更新失败');
    }
}

onMounted(() => {
  initUserInfo()
})

const handleAvatarSuccess = (url) => {
  userInfo.avatarUrl = url
  //更新 store 中的用户信息
  useUserStore().userInfo.avatarUrl = url
  avatarDialogVisible.value = false
}
</script>

<style scoped>
.user-center {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.user-info-card {
  margin-bottom: 20px;
}
</style>